/* eslint-disable */
import { IBreadcrumb } from '@/base-ui/breadcrumb/types'
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null

// 请求后端用户权限后调用本方法将菜单数组转换为路由数组
function mapMenus2Routes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  const allRoutes: RouteRecordRaw[] = []
  // 第二个参数 true 表示要递归查找文件
  // 第三个参数通过正则表达式匹配文件
  // 读取项目文件系统的所有路由并构建为 allRoutes - 所有路由
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  const _recurseGetRoutes = (menus: any[]) => {
    menus.forEach((item) => {
      if (item.type !== 2) {
        _recurseGetRoutes(item.children)
      } else {
        const route = allRoutes.find((oneRoute) => oneRoute.path === item.url)
        if (route) routes.push(route)
        if (!firstMenu) firstMenu = item
      }
    })
  }

  _recurseGetRoutes(userMenus)

  return routes
}

function getBreadcrumb(userMenus: any[], path: string): any {
  const breadcrumbs: IBreadcrumb[] = []
  getMenu8Path(userMenus, path, breadcrumbs)
  return breadcrumbs
}

/**
 * 得到页面当前路径对应的菜单权限对象并返回
 * @param userMenus 当前登录系统的用户拥有的菜单项权限
 * @param path 浏览器当前 url - 通过 useRoute().path 获得的路径
 * @returns
 */
function getMenu8Path(
  userMenus: any[],
  path: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = getMenu8Path(menu.children || [], path)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name, path: menu.url })
        breadcrumbs?.push({ name: findMenu.name, path: findMenu.url })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === path) {
      return menu
    }
  }
}

export { mapMenus2Routes, getMenu8Path, firstMenu, getBreadcrumb }
